package com.css.zfzx.fxpg.modules.economicloss.probability.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.economicloss.probability.repository.FxEconomyLossProbabilityComputeNativeRepository;
import com.css.zfzx.fxpg.modules.economicloss.probability.repository.FxEconomyLossProbabilityComputeRepository;
import com.css.zfzx.fxpg.modules.economicloss.probability.repository.entity.FxEconomyLossProbabilityComputeEntity;
import com.css.zfzx.fxpg.modules.economicloss.probability.service.FxEconomyLossProbabilityComputeService;
import com.css.zfzx.fxpg.modules.economicloss.probability.viewobjects.FxEconomyLossProbabilityComputeQueryParams;
import com.css.zfzx.fxpg.modules.economicloss.probability.viewobjects.FxEconomyLossProbabilityComputeVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageImpl;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author andy
 * @date 2020-12-08
 */
@Service
@Slf4j
public class FxEconomyLossProbabilityComputeServiceImpl implements FxEconomyLossProbabilityComputeService {

	@Autowired
    private FxEconomyLossProbabilityComputeRepository fxEconomyLossProbabilityComputeRepository;
    @Autowired
    private FxEconomyLossProbabilityComputeNativeRepository fxEconomyLossProbabilityComputeNativeRepository;

    @Override
    public JSONObject queryFxEconomyLossProbabilityComputes(FxEconomyLossProbabilityComputeQueryParams queryParams, int curPage, int pageSize) {
        Page<FxEconomyLossProbabilityComputeEntity> fxEconomyLossProbabilityComputePage = this.fxEconomyLossProbabilityComputeNativeRepository.queryFxEconomyLossProbabilityComputes(queryParams, curPage, pageSize);
        List<FxEconomyLossProbabilityComputeVO> fxEconomyLossProbabilityComputeVOList = new ArrayList<>();
        List<FxEconomyLossProbabilityComputeEntity> fxEconomyLossProbabilityComputeEntityList = fxEconomyLossProbabilityComputePage.getContent();
        for(FxEconomyLossProbabilityComputeEntity fxEconomyLossProbabilityComputeEntity : fxEconomyLossProbabilityComputeEntityList){
            FxEconomyLossProbabilityComputeVO fxEconomyLossProbabilityComputeVO = new FxEconomyLossProbabilityComputeVO();
            BeanUtils.copyProperties(fxEconomyLossProbabilityComputeEntity, fxEconomyLossProbabilityComputeVO);
            if(PlatformObjectUtils.isNotEmpty(fxEconomyLossProbabilityComputeEntity.getDamageDegree())) {
                fxEconomyLossProbabilityComputeVO.setDamageDegreeName(findByDictCodeAndDictItemCode("damageDegree", fxEconomyLossProbabilityComputeEntity.getDamageDegree()));
            }
            fxEconomyLossProbabilityComputeVOList.add(fxEconomyLossProbabilityComputeVO);
        }
        Page<FxEconomyLossProbabilityComputeVO> FxEconomyLossProbabilityComputeVOPage = new PageImpl(fxEconomyLossProbabilityComputeVOList, fxEconomyLossProbabilityComputePage.getPageable(), fxEconomyLossProbabilityComputePage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(FxEconomyLossProbabilityComputeVOPage);
        return jsonObject;
    }


    @Override
    public FxEconomyLossProbabilityComputeEntity getFxEconomyLossProbabilityCompute(String id) {
        FxEconomyLossProbabilityComputeEntity fxEconomyLossProbabilityCompute = this.fxEconomyLossProbabilityComputeRepository.findById(id).orElse(null);
         return fxEconomyLossProbabilityCompute;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxEconomyLossProbabilityComputeEntity saveFxEconomyLossProbabilityCompute(FxEconomyLossProbabilityComputeEntity fxEconomyLossProbabilityCompute) {
        String uuid = UUIDGenerator.getUUID();
        fxEconomyLossProbabilityCompute.setId(uuid);
        fxEconomyLossProbabilityCompute.setCreateUser(PlatformSessionUtils.getUserId());
        fxEconomyLossProbabilityCompute.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxEconomyLossProbabilityComputeRepository.save(fxEconomyLossProbabilityCompute);
        return fxEconomyLossProbabilityCompute;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxEconomyLossProbabilityComputeEntity updateFxEconomyLossProbabilityCompute(FxEconomyLossProbabilityComputeEntity fxEconomyLossProbabilityCompute) {
        fxEconomyLossProbabilityCompute.setUpdateUser(PlatformSessionUtils.getUserId());
        fxEconomyLossProbabilityCompute.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxEconomyLossProbabilityCompute.getId();
        FxEconomyLossProbabilityComputeEntity one = fxEconomyLossProbabilityComputeRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxEconomyLossProbabilityCompute, one);
        this.fxEconomyLossProbabilityComputeRepository.save(one);
        return fxEconomyLossProbabilityCompute;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxEconomyLossProbabilityComputes(List<String> ids) {
        List<FxEconomyLossProbabilityComputeEntity> fxEconomyLossProbabilityComputeList = this.fxEconomyLossProbabilityComputeRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(fxEconomyLossProbabilityComputeList) && fxEconomyLossProbabilityComputeList.size() > 0) {
            for(FxEconomyLossProbabilityComputeEntity fxEconomyLossProbabilityCompute : fxEconomyLossProbabilityComputeList) {
                this.fxEconomyLossProbabilityComputeRepository.delete(fxEconomyLossProbabilityCompute);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public List<FxEconomyLossProbabilityComputeEntity> getFxEconomyLossProbabilityComputes(FxEconomyLossProbabilityComputeQueryParams queryParams) {
        List<FxEconomyLossProbabilityComputeEntity> fxEconomyLossProbabilityComputes = this.fxEconomyLossProbabilityComputeNativeRepository.listFxEconomyLossProbabilityComputes(queryParams);
        return fxEconomyLossProbabilityComputes;
    }

    @Override
    public String exportExcel(FxEconomyLossProbabilityComputeQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxEconomyLossProbabilityComputeEntity> probabilityEntities = fxEconomyLossProbabilityComputeNativeRepository.listFxEconomyLossProbabilityComputes(queryParams);
            // 深拷贝
            ArrayList<FxEconomyLossProbabilityComputeVO> vos = new ArrayList<>();
            for (FxEconomyLossProbabilityComputeEntity probabilityEntity : probabilityEntities) {
                FxEconomyLossProbabilityComputeVO vo = new FxEconomyLossProbabilityComputeVO();
                BeanUtils.copyProperties(probabilityEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "经济损失风险评估-概率性损失区划", "经济损失风险评估-概率性损失区划", FxEconomyLossProbabilityComputeVO.class, "经济损失风险评估-概率性损失区划.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxEconomyLossProbabilityComputeVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxEconomyLossProbabilityComputeVO.class, params);
            List<FxEconomyLossProbabilityComputeVO> list = result.getList();
            // 批量新增
            this.saveData(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxEconomyLossProbabilityComputeVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxEconomyLossProbabilityComputeVO probabilityComputeVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + probabilityComputeVO.getRowNum() + "行" + probabilityComputeVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    private void saveData(List<FxEconomyLossProbabilityComputeVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxEconomyLossProbabilityComputeEntity probabilityComputeEntity = new FxEconomyLossProbabilityComputeEntity();
            FxEconomyLossProbabilityComputeVO probabilityComputeVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(probabilityComputeVO, probabilityComputeEntity);
            probabilityComputeEntity.setIsValid("1");
            saveOrUpdate(probabilityComputeEntity);
        }
    }

    /**
     * 保存或者修改（OBJECTID字段值相同的数据只能有一条数据）
     *
     * @param probabilityComputeEntity
     */
    @Override
    public void saveOrUpdate(FxEconomyLossProbabilityComputeEntity probabilityComputeEntity) {
        FxEconomyLossProbabilityComputeQueryParams queryParams = new FxEconomyLossProbabilityComputeQueryParams();
        queryParams.setProvince(probabilityComputeEntity.getProvince());
        queryParams.setCity(probabilityComputeEntity.getCity());
        queryParams.setArea(probabilityComputeEntity.getArea());
        queryParams.setDamageDegree(probabilityComputeEntity.getDamageDegree());
        List<FxEconomyLossProbabilityComputeEntity> probabilityComputeEntities = fxEconomyLossProbabilityComputeNativeRepository.listFxEconomyLossProbabilityComputes(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(probabilityComputeEntities)) {
            this.saveFxEconomyLossProbabilityCompute(probabilityComputeEntity);
        } else {
            if (probabilityComputeEntities.size() == 1) {
                FxEconomyLossProbabilityComputeEntity sourceProvinceEntity = probabilityComputeEntities.get(0);
                BeanUtil.copyPropertiesIgnoreNull(probabilityComputeEntity, sourceProvinceEntity);
                this.updateFxEconomyLossProbabilityCompute(sourceProvinceEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }
}
